package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"reflect"
)

func GetValidMsg(err error, obj any) string {
	ObjReflectType := reflect.TypeOf(obj)
	if errs, ok := err.(validator.ValidationErrors); ok {
		for _, e := range errs {
			if f, exit := ObjReflectType.Elem().FieldByName(e.Field()); exit {
				msg := f.Tag.Get("msg")
				return msg
			}
		}
	}
	//未自定义信息返回默认提示词
	return err.Error()
}

type User struct {
	Username string `json:"Username" binding:"required,sign" msg:"用户校验失败"`
	Age      int    `json:"Age" binding:"gt=0" msg:"请输入年龄"`
}

func signValid(fl validator.FieldLevel) bool {
	//自定义校验逻辑
	//return false
	return true
}
func main() {
	router := gin.Default()

	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		//自定义绑定器
		v.RegisterValidation("sign", signValid)
	}

	var user User
	router.POST("/", func(context *gin.Context) {
		err := context.ShouldBindJSON(&user)
		if err != nil {
			context.JSON(200, gin.H{"msg": GetValidMsg(err, &user)})
		}
		context.JSON(200, gin.H{"msg": "成功"})
	})
	router.Run(":8080")
}
